package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import dataLayer.DAOUser;
import dataLayer.DBconnect;
import model.User;
import types.ConsoleType;
import view.PanelHolder;
import view.Panelregister;
import view.loginPanel;

public class Register extends DBconnect implements ActionListener {

	private Panelregister PRform;

	private String user_name;
	private char[] password;
	private String stringPassword;

	public Register(Panelregister PRform) {
		this.PRform = PRform;

	}

	// Check on fields for register and Error message in console
	public void actionPerformed(ActionEvent e) {
		openConn();
		if (e.getActionCommand().equals("Registreren")) {
			String message = null;
			ConsoleType type = null;
			try {

				user_name = PRform.getNameField().getText();
				password = PRform.getPasswordField().getPassword();

				stringPassword = new String(password);

				if (user_name.equals(password)) {
					message = "Het wachtwoord mag niet hetzelfde zijn als de gebruikers naam";
					type = ConsoleType.ERROR;

				} else {
					// adds the new user to the database
					User u = new User(user_name, stringPassword);

					DAOUser DU = DAOUser.getInstance();
					DU.insertUser(u);

					PanelHolder ph = PanelHolder.getInstance();
					ph.remove(PRform);
					ph.add(loginPanel.getInstance());
					ph.repaint();
					ph.revalidate();
					message = "U heeft een account geregistreerd";
					type = ConsoleType.SUCCESS;
				}

				Console.getInstance().setConsole(message, type);

			} catch (Exception e2) {

			}
		}
	}

}
